package cn.com.taiji.oospub.wechat.service.impl;

import cn.com.taiji.oospub.wechat.common.tool.TimeTools;
import cn.com.taiji.oospub.wechat.entity.Courses;
import cn.com.taiji.oospub.wechat.entity.CoursesOrders;
import cn.com.taiji.oospub.wechat.entity.CoursesOrdersDetails;
import cn.com.taiji.oospub.wechat.entity.MemberBaseInfo;
import cn.com.taiji.oospub.wechat.mapper.CoursesMapper;
import cn.com.taiji.oospub.wechat.mapper.CoursesOrdersDetailsMapper;
import cn.com.taiji.oospub.wechat.service.ICoursesOrdersDetailsService;
import cn.com.taiji.oospub.wechat.service.IMealTimeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.dreamyoung.mprelation.AutoMapper;
import com.github.dreamyoung.mprelation.ServiceImpl;
import jxl.Workbook;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.VerticalAlignment;
import jxl.format.*;
import jxl.write.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.time.LocalDate;
import java.util.List;

import static cn.com.taiji.oospub.wechat.entity.CoursesOrders.CoursesOrderStatus.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yzd
 * @since 2020-10-28
 */
@Service
public class CoursesOrdersDetailsServiceImpl extends ServiceImpl<CoursesOrdersDetailsMapper, CoursesOrdersDetails> implements ICoursesOrdersDetailsService {
    @Autowired
    private CoursesOrdersDetailsMapper coursesOrdersDetailsMapper;
    @Autowired
    private AutoMapper autoMapper;
    @Autowired
    private CoursesMapper coursesMapper;
    @Autowired
    private IMealTimeService mealTimeService;

    @Override
    public CoursesOrdersDetails getCoudetail(QueryWrapper<CoursesOrdersDetails> coursesOrdersDetailsModel) {
        coursesOrdersDetailsModel.orderByDesc("lastChanged");
        return coursesOrdersDetailsMapper.selectOne(coursesOrdersDetailsModel);
    }

    @Override
    public List<CoursesOrdersDetails> queryList(QueryWrapper<CoursesOrdersDetails> queryModel) {
        List<CoursesOrdersDetails> coursesOrdersDetails = coursesOrdersDetailsMapper.selectList(queryModel);
        for (CoursesOrdersDetails course : coursesOrdersDetails) {
            autoMapper.mapperEntity(course);
        }
        return coursesOrdersDetails;
    }

    @Override
    public List<CoursesOrdersDetails> findByProperty(String columnName, String value) {
        QueryWrapper<CoursesOrdersDetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(columnName, value);
        List<CoursesOrdersDetails> coursesOrdersDetails = coursesOrdersDetailsMapper.selectList(queryWrapper);
        for (CoursesOrdersDetails course : coursesOrdersDetails) {
            autoMapper.mapperEntity(course);
        }
        return coursesOrdersDetails;
    }

    @Override
    public void exportExcelDetail(MemberBaseInfo member, HttpServletResponse response) {

        try {
            String fileName = ""; //文件名
            fileName = new String(("月度报告.xls").getBytes("UTF-8"), "iso8859-1");
            OutputStream os = response.getOutputStream();
            response.reset();
            response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8080");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

            //大标题字体(订单清单表.xls)
            WritableCellFormat wcfTitle = new WritableCellFormat();
            WritableFont BigTitleFont = new WritableFont(WritableFont.createFont("宋体"), 18, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
            wcfTitle.setAlignment(jxl.format.Alignment.CENTRE);
            wcfTitle.setVerticalAlignment(VerticalAlignment.CENTRE);
            wcfTitle.setFont(BigTitleFont);
            wcfTitle.setBorder(Border.ALL, BorderLineStyle.THIN);

            //表头字体
            WritableCellFormat wcfGrid = new WritableCellFormat();
            WritableFont gridTitleFont = new WritableFont(WritableFont.createFont("宋体"), 10, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
            wcfGrid.setAlignment(jxl.format.Alignment.CENTRE);
            wcfGrid.setVerticalAlignment(VerticalAlignment.CENTRE);
            wcfGrid.setFont(gridTitleFont);
            wcfGrid.setBorder(Border.ALL, BorderLineStyle.THIN);
            wcfGrid.setWrap(true);

            //内容字体
            WritableCellFormat wcfL = new WritableCellFormat();
            wcfL.setAlignment(jxl.format.Alignment.LEFT);
            wcfL.setVerticalAlignment(VerticalAlignment.CENTRE);
            wcfL.setBorder(Border.ALL, BorderLineStyle.THIN);
            wcfL.setWrap(true);

            WritableCellFormat wcfLNumber = new WritableCellFormat();
            wcfLNumber.setAlignment(jxl.format.Alignment.RIGHT);
            wcfLNumber.setVerticalAlignment(VerticalAlignment.CENTRE);
            wcfLNumber.setBorder(Border.ALL, BorderLineStyle.THIN);
            wcfLNumber.setWrap(true);

            WritableWorkbook wb = Workbook.createWorkbook(os);
            WritableSheet sheet = wb.createSheet("月度报告", 0);

            //大标题(消费明细统计表)
            sheet.mergeCells(0, 0, 15, 0);
            sheet.setRowView(0, 1000);
            sheet.addCell(new Label(0, 0, "月度报告", wcfTitle));


            //大标题(此报表的主要功能为，用于记录限定的日期记录内，会员消费的所有菜品品项销售数量、金额的明细（不包含消费冲账明细和退菜明细）)
            sheet.mergeCells(0, 1, 15, 1);
            sheet.setRowView(1, 500);
            sheet.addCell(new Label(0, 1, "此报表的主要功能为，用于记录限定的日期记录内，会员消费的所有菜品品项销售数量、金额的明细（不包含消费冲账明细和退菜明细,金额为优惠前金额）", wcfGrid));


            //大标题(开始时间：2017-03-04 03:10	)
            sheet.mergeCells(0, 2, 2, 2);
            sheet.setRowView(2, 500);
            sheet.addCell(new Label(0, 2, "开始时间：" + LocalDate.now().minusDays(30), wcfGrid));


            //大标题(打印时间：2017-08-14	)
            sheet.mergeCells(8, 2, 9, 2);
            sheet.addCell(new Label(8, 2, "打印时间：" + LocalDate.now(), wcfGrid));


            //大标题(结束时间：2017-08-14 03:10		)
            sheet.mergeCells(0, 3, 2, 3);
            sheet.setRowView(3, 500);
            sheet.addCell(new Label(0, 3, "结束时间：" + LocalDate.now(), wcfGrid));


            sheet.mergeCells(8, 3, 9, 3);
            sheet.addCell(new Label(8, 3, "打印人员:" + member.getName(), wcfGrid));

            //表头
            sheet.addCell(new Label(0, 4, "订单编号：", wcfGrid));
            sheet.setColumnView(0, 14);
            sheet.addCell(new Label(1, 4, "顾客名称：", wcfGrid));
            sheet.setColumnView(1, 14);
            sheet.addCell(new Label(2, 4, "顾客编号：", wcfGrid));
            sheet.setColumnView(2, 14);
            sheet.addCell(new Label(3, 4, "餐厅名称：", wcfGrid));
            sheet.setColumnView(3, 20);
            sheet.addCell(new Label(4, 4, "餐次：", wcfGrid));
            sheet.setColumnView(4, 15);
            sheet.addCell(new Label(5, 4, "业务类型：", wcfGrid));
            sheet.setColumnView(5, 10);
            sheet.addCell(new Label(6, 4, "菜品名称：", wcfGrid));
            sheet.setColumnView(6, 10);
            sheet.addCell(new Label(7, 4, "品项编码：", wcfGrid));
            sheet.setColumnView(7, 10);
            sheet.addCell(new Label(8, 4, "计量单位：", wcfGrid));
            sheet.setColumnView(8, 10);
            sheet.addCell(new Label(9, 4, "原价：", wcfGrid));
            sheet.setColumnView(9, 10);
            sheet.addCell(new Label(10, 4, "数量：", wcfGrid));
            sheet.setColumnView(10, 20);
            sheet.addCell(new Label(11, 4, "消费金额：", wcfGrid));
            sheet.setColumnView(11, 20);
//            sheet.addCell(new Label(12, 4, "人工折扣：",wcfGrid));
//            sheet.setColumnView(12, 20);
            sheet.addCell(new Label(12, 4, "消费类型：", wcfGrid));
            sheet.setColumnView(12, 20);
            sheet.addCell(new Label(13, 4, "消费时间：", wcfGrid));
            sheet.setColumnView(13, 20);
            sheet.addCell(new Label(14, 4, "顾客手机：", wcfGrid));
            sheet.setColumnView(14, 14);

            //根据条件查找

            QueryWrapper<CoursesOrdersDetails> orderWrapper = new QueryWrapper<>();
            orderWrapper.eq("creator", member.getId());
            orderWrapper.eq("is_effective", true);
            orderWrapper.ge("last_changed", LocalDate.now().minusDays(30));
//            orderWrapper.le("last_changed", LocalDateTime.of(LocalDate.now(), LocalTime.MAX));[
            List<CoursesOrdersDetails> coursesOrdersDetailsList = coursesOrdersDetailsMapper.selectList(orderWrapper);
            int row = 5;
            int col = 0;
            if (null != coursesOrdersDetailsList && coursesOrdersDetailsList.size() > 0) {
                //菜品细目
                Double sumAmount = 0.00d;
                Double number = 0.00;
                for (int i = 0; i < coursesOrdersDetailsList.size(); i++) {
                    CoursesOrdersDetails coursesOrdersDetails = autoMapper.mapperEntity(coursesOrdersDetailsList.get(i));
                    if (!coursesOrdersDetails.getMainOrder().getStatus().equals(YZF)
                            && !coursesOrdersDetails.getMainOrder().getStatus().equals(BCZ)
                            && !coursesOrdersDetails.getMainOrder().getStatus().equals(DDYWC)
                            && !coursesOrdersDetails.getMainOrder().getStatus().equals(BCWC)) {
                        continue;
                    }
                    sheet.addCell(new Label(col++, row, coursesOrdersDetails.getMainOrder().getOrderCode(), wcfL));
                    sheet.addCell(new Label(col++, row, coursesOrdersDetails.getCreatorInfo().getName(), wcfL));
                    sheet.addCell(new Label(col++, row, coursesOrdersDetails.getCreatorInfo().getIdNumber(), wcfL));
                    sheet.addCell(new Label(col++, row, autoMapper.mapperEntity(coursesOrdersDetails.getCreatorInfo()).getSchool().getNameZh(), wcfL));
                    number += coursesOrdersDetails.getQuantity();
                    Courses courses = coursesMapper.selectById(coursesOrdersDetails.getCourseId());
                    if (courses != null) {
                        sheet.addCell(new Label(col++, row, mealTimeService.findByProper("code", courses).getName(), wcfL));
                        sheet.addCell(new Label(col++, row, courses.getBusinessName(), wcfL));
                        sheet.addCell(new Label(col++, row, courses.getNameCh(), wcfL));
                        sheet.addCell(new Label(col++, row, courses.getPosNo(), wcfL));
                        sheet.addCell(new Label(col++, row, courses.getPosUnit(), wcfL));
                        sumAmount += courses.getPrice();
                        sheet.addCell(new Label(col++, row, courses.getPrice().toString(), wcfL));
                        sheet.addCell(new Label(col++, row, coursesOrdersDetails.getQuantity().toString(), wcfL));
                        sheet.addCell(new Label(col++, row, String.valueOf(courses.getPrice() * coursesOrdersDetails.getQuantity()), wcfL));
                    }


//                    sheet.addCell(new Label(col++, row, "0",wcfL));
                    sheet.addCell(new Label(col++, row, CoursesOrders.PayWay.valueOf(coursesOrdersDetails.getMainOrder().getPayWay().toString()).getValue(), wcfL));

                    sheet.addCell(new Label(col++, row, TimeTools.localDateTime2String(coursesOrdersDetails.getLastChanged(), "yyyy-MM-dd HH:mm:ss"), wcfL));//
                    sheet.addCell(new Label(col++, row, coursesOrdersDetails.getCreatorInfo().getMobile(), wcfL));
                    row++;
                    col = 0;
                }
                sheet.addCell(new Label(col++, row, "合计", wcfL));//
                sheet.addCell(new Label(col++, row, "", wcfL));//
                sheet.addCell(new Label(col++, row, "", wcfL));//
                sheet.addCell(new Label(col++, row, "", wcfL));//
                sheet.addCell(new Label(col++, row, "", wcfLNumber));//
                sheet.addCell(new Label(col++, row, "", wcfL));//
                sheet.addCell(new Label(col++, row, "", wcfL));//
                sheet.addCell(new Label(col++, row, "", wcfL));//
                sheet.addCell(new Label(col++, row, "", wcfL));//
                sheet.addCell(new Label(col++, row, "", wcfL));//
                sheet.addCell(new Label(col++, row, number.toString(), wcfL));//
                sheet.addCell(new Label(col++, row, sumAmount.toString(), wcfL));//
                sheet.addCell(new Label(col++, row, "", wcfL));//
                sheet.addCell(new Label(col++, row, "", wcfL));//
                sheet.addCell(new Label(col++, row, "", wcfL));//
                sheet.addCell(new Label(col++, row, "", wcfL));//
            }
            wb.write();
            wb.close();
            os.flush();
            os.close();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (WriteException e) {
            e.printStackTrace();
        }
    }
}
